﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.ObjectBuilder;

namespace MetaContainer.Unity
{
   /// <summary>
   /// Provided factory methid functionality used by MetaContainer adapter.
   /// </summary>
   internal sealed class FactoryMethodExtension : UnityContainerExtension
   {
      private FactoryBuildKeyMappingStrategy _strategy = new FactoryBuildKeyMappingStrategy();

      protected override void Initialize()
      {
         Context.Strategies.Add(_strategy, UnityBuildStage.Setup);   
      }

      /// <summary>
      /// Registres factory method in the container.
      /// </summary>
      /// <param name="from">Service interface type.</param>
      /// <param name="factoryMethod">Method producing service implementations.</param>
      /// <param name="lifetimeManager">Lifetime/scope type.</param>
      internal void RegisterFactoryMethod(Type from, Func<string, object> factoryMethod, LifetimeManager lifetimeManager)
      {         
         _strategy.RegisterFactoryProducedType(from);
         Context.Policies.Set<IBuildPlanPolicy>(
             new FactoryMethodBuildPlanPolicy(factoryMethod, lifetimeManager),
             new NamedTypeBuildKey(from));
      }

   }
}
